iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0
佛心分享-刷題不只是刷題

C/C++ 刷題30天系列 第 11

Day11__C語言刷LeetCode

  • 分享至 

  • xImage
  •  

1779. Find Nearest Point That Has the Same X or Y Coordinate

tags: Easy、Point

You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.
Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.
The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).

解法:

#define absolute(a) ((a) > 0 ? (a) : (-a))
int nearestValidPoint(int x, int y, int** points, int pointsSize, int* pointsColSize) {
    int index = -1;
    int dis, min = 1e4; 

    for (int i = 0; i < pointsSize; i++) {
        if (points[i][0] == x || points[i][1] == y) {
            int diffx = points[i][0] - x;
            int diffy = points[i][1] - y;
            dis = absolute(diffx) + absolute(diffy);
            if (dis < min) {
                min = dis;
                index = i;
            }
        }
    }
    return index;
}

1876. Substrings of Size Three with Distinct Characters

tags: Easy、Sizeof

A string is good if there are no repeated characters.
Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
A substring is a contiguous sequence of characters in a string.

解法:

int countGoodSubstrings(char* s) {
    int subnums = 0;
    if (strlen(s) < 3) {
        return subnums;
    }

    for (int i = 0; s[i+2] != '\0'; i++) {
        if (s[i] != s[i+1] && s[i] != s[i+2] && s[i+1] != s[i+2]) {
            subnums += 1;
        }
    }
    return subnums;
}

上一篇
Day10__C語言刷LeetCode
下一篇
Day12__C語言刷LeetCode
系列文
C/C++ 刷題30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言